import 'package:flutter/material.dart';
import 'package:flutter_study/pages/chapter9/chapter9_page.dart';

class RoutingSwitchAnimationRoute extends StatefulWidget {
  const RoutingSwitchAnimationRoute({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _RoutingSwitchAnimationRouteState();
}

class _RoutingSwitchAnimationRouteState
    extends State<RoutingSwitchAnimationRoute> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('自定义路由切换动画'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () => Navigator.of(context).push(
            FadeRoute(
                isActive: false, builder: (context) => const Chapter9Page()),
          ),
          child: const Text("自定义路由切换动画"),
        ),
      ),
    );
  }
}

class FadeRoute extends PageRoute {
  final WidgetBuilder builder;

  @override
  final Duration transitionDuration;

  @override
  final bool opaque;

  @override
  final bool barrierDismissible;

  @override
  final Color? barrierColor;

  @override
  final String? barrierLabel;

  @override
  final bool maintainState;

  @override
  final bool isActive;

  FadeRoute(
      {required this.builder,
      this.transitionDuration = const Duration(seconds: 1),
      this.opaque = true,
      this.barrierDismissible = false,
      this.isActive = false,
      this.barrierColor,
      this.barrierLabel,
      this.maintainState = false});

  @override
  Widget buildPage(BuildContext context, Animation<double> animation,
          Animation<double> secondaryAnimation) =>
      builder(context);

  @override
  Widget buildTransitions(BuildContext context, Animation<double> animation,
      Animation<double> secondaryAnimation, Widget child) {
    if (isActive) {
      return FadeTransition(
        opacity: animation,
        child: builder(context),
      );
    } else {
      //是返回，则不应用过渡动画
      return builder(context);
    }
  }
}
